using System;
using System.Globalization;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Security;
using TemplateLibraryConnector.Utility;

namespace TemplateLibraryConnector.Features.ContentTypeAssociation
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("acaa127d-c30e-4a6b-b398-983d7ac70f4e")]
    public class ContentTypeAssociationEventReceiver : SPFeatureReceiver
    {
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            var webApp = properties.Feature.Parent as SPWebApplication;
            var featureTitle = properties.Definition.GetTitle(CultureInfo.CurrentCulture);

            if (webApp != null)
                foreach (var job in webApp.JobDefinitions.Where(job => job.Name.StartsWith(featureTitle)))
                {
                    job.Delete();
                }

            var ctJob = new ContentTypeAssociationJob(featureTitle, webApp);

            var schedule = new SPHourlySchedule { BeginMinute = 15, EndMinute = 30 };
            ctJob.IsDisabled = false;

            ctJob.Schedule = schedule;
            ctJob.Update();

        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            var webApp = properties.Feature.Parent as SPWebApplication;

            if (webApp != null)
                foreach (var job in webApp.JobDefinitions.Where(job => job.Name.StartsWith(properties.Definition.GetTitle(CultureInfo.CurrentCulture))))
                {
                    job.Delete();
                }
        }
    }
}
